/*
 * @Descripttion:
 * @Author: voanit
 * @Date: 2022-05-29 11:09:23
 * @LastEditors: voanit
 * @LastEditTime: 2022-05-29 16:44:31
 */
// import { ThunkAction } from 'redux-thunk'
// import { RootState } from '..'
import { RootThunkAction } from '..'

import axios from 'axios'
export type TodoAction =
  | {
      type: 'ADD_TODO' // 字面量类型
      name: string
    }
  | {
      type: 'DEL_TODO'
      id: number
    }
  | {
      type: 'CHANGE_STATE_TODO'
      payload: {
        id: number
        newIsDone: boolean
      }
    }
  | {
      type: 'INIT_TODO'
      data: []
    }
export const delTodo = (id: number): RootThunkAction => {
  // ): ThunkAction<void, RootState, unknown, TodoAction> => {
  // return {
  //   type: 'DEL_TODO',
  //   id,
  // }
  return (dispatch) => {
    dispatch({
      type: 'DEL_TODO',
      id,
    })
  }
}

export const addTodo = (name: string): TodoAction => {
  return {
    type: 'ADD_TODO',
    name,
  }
}

export const changeStateTodo = (id: number, newIsDone: boolean): TodoAction => {
  return {
    type: 'CHANGE_STATE_TODO',
    payload: {
      id,
      newIsDone,
    },
  }
}

export function getTodos(): RootThunkAction {
  // export function getTodos(): ThunkAction<void, RootState, unknown, TodoAction> {
  return async (dispatch) => {
    const res = await axios.get(
      'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/todos'
    )
    // 异步操作
    dispatch({
      type: 'INIT_TODO',
      data: res.data.data,
    })
  }
}
